//
//  AddNewAddressViewController.m
//  FactorySale
//
//  Created by 主事丫环 on 2020/3/27.
//  Copyright © 2020 主事丫环. All rights reserved.
//

#import "AddNewAddressViewController.h"
#import "HFTiXianTFCell.h"
#import "HFDefaultAddressCell.h"
#import "WQTableViewCell.h"
#import "NetLoadAreaPickerViewController.h"
#import "AddAreaModel.h"

#import "CommonPopViewController.h"

@interface AddNewAddressViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSString *_name;
    NSString *_phone;
    NSString *_area;
    NSString *_address;
    NSInteger _isDefault;
    NSString *_WQaddress;
    NSString *shengshiqu;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *mydateSource;
@property (nonatomic, strong) NSArray *titleArray;
@property (nonatomic, strong) NSArray *placeholderArray;
@property (nonatomic, strong) NSArray *contentArray;
@property (nonatomic, assign) BOOL iscansele;
@property (nonatomic, strong) NSMutableArray *muarr;
@property (nonatomic, strong) UIView *tabFootView;
@property (nonatomic, assign) BOOL isSelected;
@property (nonatomic, strong) UIButton *setDefBtn;

@end

@implementation AddNewAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"新建地址";
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];
    //self.view.backgroundColor = Main_BackGroundColor;
    self.view.backgroundColor = [UIColor whiteColor];
    
    _titleArray = @[@"姓名:", @"联系方式:", @"收货地址:", @"详细地址:"];
    _placeholderArray = @[@"请输入姓名", @"请输入电话", @"请选择收货地址", @"请输入详细地址"];
    
    self.mydateSource  = [NSMutableArray arrayWithCapacity:1];
    
    if (_muarr.count >0) {
        self.mydateSource =_muarr;
        [_tableView reloadData];
    }
    
    [self configNavi];
    [self.view addSubview:self.tableView];
    [self showtabFootView];
    
    // Do any additional setup after loading the view.
}

- (void)configNavi {
    if (self.model) {
        self.title = @"编辑";
        _name = _model.name;
        _phone = _model.phone;
        
        //判断字符串是否包含空格
        NSRange range = [_model.address rangeOfString:@" "];
        NSLog(@"传过来的地址是什么 %@", _model.address);
        
        if (range.location != NSNotFound ) {
            //有空格
            NSLog(@"有空格");
            NSArray *stringUrlOne = [_model.address componentsSeparatedByString:@" "];
            _area = stringUrlOne[0];
            NSLog(@"stringUrlOne[0] = %@",stringUrlOne[0]);
            _address = stringUrlOne[1];
            NSLog(@"stringUrlOne[1] = %@",stringUrlOne[1]);
        } else {
            //没有空格
            NSLog(@"没有空格");
            _area = _model.address;
            _address = _model.address;
        }
        
        if (_isDefault == 1) {
            self.setDefBtn.selected = YES;
            [self.setDefBtn setImage:imgname(@"选中") forState:UIControlStateNormal];
        } else {
            self.setDefBtn.selected = NO;
            [self.setDefBtn setImage:imgname(@"未选中") forState:UIControlStateNormal];
        }
        _contentArray = @[_name, _phone, _area, _address];
        //shengshiqu = [NSString stringWithFormat:@"%@-%@-%@",_model.province,_model.city,_model.area];
        [self AddNewPageRiightSelBtn]; //删除按钮
    } else {
        self.title = @"新建地址";
        _contentArray = @[@"", @"", @"", @""];
    }
}

-(void)showtabFootView{
    
    self.tabFootView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KWIDTH, 166)];
    
    //设置默认按钮
    UIButton *setDefBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    setDefBtn.frame = CGRectMake(KWIDTH - 130, 26 , 120, 30);
    setDefBtn.tag = 1000;
    [setDefBtn setTitle:@"  设置默认地址" forState:UIControlStateNormal];
    setDefBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [setDefBtn setImage:imgname(@"未选中") forState:UIControlStateNormal];
    [setDefBtn setImage:imgname(@"选中") forState:UIControlStateSelected];
    [setDefBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [setDefBtn addTarget:self action:@selector(setDefBtnClickAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.tabFootView addSubview:setDefBtn];
    self.setDefBtn = setDefBtn;
    
    UIButton *saveBut  = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [saveBut setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [saveBut setBackgroundImage:imgname(@"saveBtnBackImg") forState:UIControlStateNormal];
    [saveBut setTitle:@"保存" forState:(UIControlStateNormal)];
    saveBut.frame = CGRectMake(50, 109.5, kScreen_Width - 100, 44);
    saveBut.titleLabel.font = [UIFont systemFontOfSize:15];
//    saveBut.layer.masksToBounds = YES;
//    saveBut.layer.cornerRadius = 4;
    [self.tabFootView addSubview:saveBut];
    
    [saveBut addTarget:self action:@selector(submitBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
    self.tableView.tableFooterView = self.tabFootView;
}

//新建地址 右上角 删除按钮
- (void)AddNewPageRiightSelBtn {
    [self.rightbutton setTitle:@" 删除" forState:(UIControlStateNormal)];
    [self.rightbutton setTitleColor:[UIColor colorWithHexString:@"#1EB491"] forState:(UIControlStateNormal)];
    [self.rightbutton setImage:imgname(@"AddNewAddImg") forState:UIControlStateNormal];
    [self.rightbutton addTarget:self action:@selector(rightButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)rightButtonAction:(UIButton *)button {
    kWeakSelf;
    CommonPopViewController *popVC = [CommonPopViewController new];
    popVC.message = @"确定要删除当前地址信息吗？";
    popVC.cancleBtnTitle = @"取消";
    popVC.confirmBtnTitle = @"确定";
    popVC.confirmBtnClick = ^{
        [weakSelf deleteAddressData];
    };
    [self presentViewController:popVC animated:YES completion:nil];
}

//删除收货地址 数据请求
- (void)deleteAddressData {
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithCapacity:1];
    param[@"id"] = self.model.id;
    
    [NetWorkTool POST:deleteAdd param:param success:^(id dic) {
        NSLog(@"打印一下 删除数据 是否调用成功 %@", dic);
        ShowToastWithText(dic[@"msg"]);
        [self.navigationController popViewControllerAnimated:YES];
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
}

- (void)setDefBtnClickAction:(UIButton *)button {
    if (self.isSelected) {
        _isSelected = NO;
        _isDefault = 0;
        NSLog(@"按钮没有被选中 _isDefault = %ld", (long)_isDefault);
        [self.setDefBtn setImage:imgname(@"未选中") forState:UIControlStateNormal];
    } else {
        _isSelected = YES;
        _isDefault = 1;
        NSLog(@"按钮被选中 _isDefault = %ld", (long)_isDefault);
        [self.setDefBtn setImage:imgname(@"选中") forState:UIControlStateNormal];
    }
}

- (void)requestAddAddressData {
    
    if (strIsEmpty(_name)) {
        ShowToastWithText(@"请填写姓名");
        return;
    }
    
    if (strIsEmpty(_phone)) {
        ShowToastWithText(@"请填写联系方式");
        return;
    }
    
    if (strIsEmpty(shengshiqu)) {
        ShowToastWithText(@"请选择所在地区");
        return;
    }
    
    if (strIsEmpty(_address)) {
        ShowToastWithText(@"请填写详细地址");
        return;
    }
    
    if(![_name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length) {
        ShowToastWithText(@"名字不能全是空格");
        return;
    }
    
    if(![_address stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length) {
        ShowToastWithText(@"详细地址不能全是空格");
        return;
    }
    
    //去除字符串中空格
    _phone = [_phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![self isMobileNumberOnly:_phone]) {
        ShowToastWithText(@"请输入正确手机号");
        return;
    }
    
    NSArray  *array = [shengshiqu componentsSeparatedByString:@"-"];
    
    NSDictionary *dic = @{
        @"address":[NSString stringWithFormat:@"%@%@%@",_area,@" ",safe(_address)],
        //@"address":safe(_address),
        //@"province":array[0],
        //@"city":array[1],
        //@"area":array[2],
        @"is_default":@(_isDefault),
        @"name":_name,
        @"phone":_phone
    };
    kWeakSelf;
    NSString *json = [HFTools toJSONString:dic];
    NSDictionary *mudci = @{@"data":json};
    [MBProgressHUD showHUDAddedTo:self.view  animated:YES];

    [NetWorkTool POST:addFactoryAddress param:mudci success:^(id dic) {
        NSLog(@"%@", dic);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [weakSelf leftClick];
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:YES];
}

- (void)requestEditAddressData {
    
    if (strIsEmpty(_name)) {
        ShowToastWithText(@"请填写收货人姓名");
        return;
    }
    
    if (strIsEmpty(_phone)) {
        ShowToastWithText(@"请填写收货人电话");
        return;
    }
    
    if (self.model) {
        if (strIsEmpty(_model.address)) {
            ShowToastWithText(@"请选择收货人省市区");
            return;
        }
    } else {
        if (strIsEmpty(shengshiqu)) {
            ShowToastWithText(@"请选择收货人省市区");
            return;
        }
    }
    
    if (strIsEmpty(_address)) {
        ShowToastWithText(@"请填写收货人详细地址");
        return;
    }
    
    if(![_name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length) {
        ShowToastWithText(@"名字不能全是空格");
        return;
    }
    
    if(![_address stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length) {
        ShowToastWithText(@"详细地址不能全是空格");
        return;
    }
    
    //去除字符串中空格
    _phone = [_phone stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (![self isMobileNumberOnly:_phone]) {
        ShowToastWithText(@"请输入正确手机号");
        return;
    }
    
    NSArray  *array = [shengshiqu componentsSeparatedByString:@"-"];
    NSDictionary *dic = @{
        @"address":[NSString stringWithFormat:@"%@%@%@",_area,@" ",safe(_address)],
        //@"address":safe(_address),
        //@"province":array[0],
        //@"city":array[1],
        //@"area":array[2],
        @"is_default":@(_isDefault),
        @"name":NOTNIL(_name),
        @"phone":NOTNIL(_phone),
        @"id":NOTNIL(_model.id)
    };
    
    NSString *json = [HFTools toJSONString:dic];
    NSDictionary *dicccc = @{@"data":json};
    kWeakSelf;
    [MBProgressHUD showHUDAddedTo:self.view  animated:YES];

    [NetWorkTool POST:updateAdd param:[dicccc mutableCopy] success:^(id dic) {
        NSLog(@"____%@", dic);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [weakSelf leftClick];
    } other:^(id dic) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } fail:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } needUser:YES];
}

#pragma mark -- click点击事件
- (void)submitBtnClick:(UIButton *)sender {
    NSLog(@"保存");
    if (self.model) {
        [self requestEditAddressData];
    } else {
        [self requestAddAddressData];
    }
}

#pragma mark -- tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _titleArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HFTiXianTFCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HFTiXianTFCell" forIndexPath:indexPath];
    cell.jinruimage.hidden = YES;
    if (indexPath.row ==2 ) {
        cell.contentTF.tag = 777;
        cell.contentTF.userInteractionEnabled = NO;
        cell.selebut.hidden = NO;
        cell.jinruimage.hidden = NO;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell configDataWithTitle:_titleArray[indexPath.row] placeHolder:_placeholderArray[indexPath.row] content:_contentArray[indexPath.row]];
    
    if (indexPath.row == 0) {
        cell.contentTF.delegate = self;
        [cell.contentTF addTarget:self action:@selector(nametextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    
    if (indexPath.row == 1) {
        cell.contentTF.delegate = self;
        cell.contentTF.keyboardType = UIKeyboardTypeNumberPad;
        [cell.contentTF addTarget:self action:@selector(phonetextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    
    if (indexPath.row == 2 ) {
        if (!strIsEmpty(_WQaddress)) {
            cell.contentTF.text = _WQaddress;
            self->_area = _WQaddress;
        }
    }
    
    if (indexPath.row == 3) {
        cell.contentTF.delegate = self;
        [cell.contentTF addTarget:self action:@selector(addresstextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    
    cell.inputContentBlock = ^(NSString * _Nonnull content) {
        switch (indexPath.row) {
            case 0:
                self->_name = content;
                break;
            case 1:
                self->_phone = content;
                break;
            case 2:
                [self locationAction];
                break;
            case 3:
                self->_address = content;
                break;
            default:
                break;
        }
    };
    return cell;
}

//姓名
- (void)nametextFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 5;
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

//联系方式
- (void)phonetextFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 11;
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

//联系方式
- (void)addresstextFieldDidChange:(UITextField *)textField {
    NSString *toBeString = textField.text;
    
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    CGFloat maxLength = 20;
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (toBeString.length > maxLength) {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:maxLength];
            if (rangeIndex.length == 1){
                textField.text = [toBeString substringToIndex:maxLength];
            } else {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, maxLength)];
                textField.text = [toBeString substringWithRange:rangeRange];
            }
        }
    }
}

#pragma mark -- 地区选择
-(void)locationAction{
    NetLoadAreaPickerViewController * loadAreaVC = [[NetLoadAreaPickerViewController alloc]init];
    kWeakSelf;
    loadAreaVC.selectedBlock = ^(NetLoadAreaModel *areaModel) {
        KMyLog(@"选中的地址%@",areaModel);
        AddAreaModel *model = [[AddAreaModel alloc]init];
        model.area = [NSString stringWithFormat:@"%@%@%@", areaModel.provinceName, areaModel.cityName, areaModel.districtName];
        model.idstr = areaModel.districtCode;
        model.isdelde = @"0";
        self->_WQaddress = model.area;
        self->shengshiqu = [NSString stringWithFormat:@"%@-%@-%@",areaModel.provinceCode,areaModel.cityCode,areaModel.districtCode];
        [weakSelf.tableView reloadData];
    };
    if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0) {
        loadAreaVC.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    } else {
        loadAreaVC.modalPresentationStyle=UIModalPresentationCurrentContext;
    }
    [self presentViewController:loadAreaVC animated:NO completion:^{
        
    }];
    return;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _titleArray.count) {
        HFDefaultAddressCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.selectBtn.selected = !cell.selectBtn.selected;
        _isDefault = cell.selectBtn.selected?1:0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _titleArray.count) {
        return 54;
    }
    return 49;
}

#pragma mark -- 懒加载
- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviHeight, ScreenW, ScreenH-kNaviHeight) style:(UITableViewStylePlain)];
        _tableView.backgroundColor = [UIColor colorWithHexString:@"eeeeee"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 40, 0);
        if (iOS11) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        _tableView.tableFooterView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 48;
        [_tableView registerNib:[UINib nibWithNibName:@"HFTiXianTFCell" bundle:nil] forCellReuseIdentifier:@"HFTiXianTFCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"HFDefaultAddressCell" bundle:nil] forCellReuseIdentifier:@"HFDefaultAddressCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"WQTableViewCell" bundle:nil] forCellReuseIdentifier:@"WQTableViewCell"];
    }
    return _tableView;
}

- (BOOL)isMobileNumberOnly:(NSString *)mobileNum {
    NSString * MOBILE = @"^((10[0-9])|(11[0-9])|(12[0-9])|(13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if ([regextestmobile evaluateWithObject:mobileNum] == YES) {
        return YES;
    } else {
        return NO;
    }
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
